<?php
namespace My\Controller;

use Utuo\BackgroundController;

class DistributionShopCertificateController extends BackgroundController {
	
	protected $types = array(
		'1' => '代理证书',
		'2' => '金牌会员证书',
	);
	
	public function _initialize() {
		$this->setControllerTitle("证书模板配置");
		$this->setActionTitle(array(
				'index' => "证书模板配置",
				'agentIndex' => "代理证书模板配置",
				'dealerIndex' => "金牌会员证书模板配置",
		));
		foreach ( $this->types as $k => $v ) {
			$this->setLinkNav($v.'配置', U('DistributionShopCertificate/index', 'type='.$k));			
		}
		$this->setActionNav('index');
	}
	
	/**
	 * 证书模板配置
	 * @see \Utuo\BackgroundController::indexAction()
	 */
	public function indexAction() {
		$type = I('type', 1, "intval");
		$m = M("DistributionShopCertificate");
		$certificate = $m->where('cid=%d and type=%d', $this->aid, $type)->find();
		if ( false === $certificate) {
			$this->error('查询发生错误');
		} elseif ( $certificate == null) {
			$certificate = array(
					'cid' => $this->aid,
					'type' => $type,
					'img' => '',
					'config' => serialize(array()),
			);
			$id = $m->add($certificate);
			if ( false !== $id ) {
				$certificate['id'] = $id;
			} else {
				$this->error('出初化数据失败');
			}
		}
		$certificate['config'] = unserialize($certificate['config']);
		$certificate['jsonConfig'] = json_encode($certificate['config']);
		$certificate['type'] = $type;
		$this->assign('distributionShopCertificate', $certificate);
		$this->display();
	}
	
	/**
	 * 证书模板配置提交
	 */
	public function indexPostAction() {
		$d = D("DistributionShopCertificate");
		if ( $d->create() ) {
			if (false !== $d->save()) {
				$this->ajaxSuccess("修改成功！");
			} else {
				$this->ajaxError("修改失败！");
			}
		} else {
			$this->ajaxError($d->getError());
		}
	}
	
	/**
	 * 代理商证书设置
	 */
	public function dealerIndexAction() {
		$type = 2;
		$dealerId = I("id", 0, "intval");
		$dealer = M("Dealer")->where("id=%d and cid=%d", $dealerId, $this->aid)->find();
		if ( $dealer ) {
			/* 默认设置 */
			$m = M("DistributionShopCertificate");
			$certificate = $m->where('cid=%d and type=%d', $this->aid, $type)->find();
			$dealer['certificate_img'] = $certificate['img'];
			/* 代理配置 */
			if ( empty($dealer['certificateConfig']) ) {
				$dealer['certificateConfig'] = unserialize($certificate['config']);
			} else {
				$dealer['certificateConfig'] = unserialize($dealer['certificateConfig']);
			}
			$dealer['jsonConfig'] = json_encode($dealer['certificateConfig']);
		} else {
			$this->error("未找到金牌会员,请先选择金牌会员再进入证书设置.");
		}
		$this->assign("dealer", $dealer);
		$this->display();
	}
	
	/**
	 * 金牌会员证书提交设置
	 */
	public function dealerIndexPostAction() {
		$agentId = I("id", 0, "intval");
		$config = I("config", array());
		$config = serialize($config);
		$img = I("img", "");
		$certificateImg = I("certificateImg", "");
		if ($certificateImg) {
			if ( strpos($certificateImg, 'http') !== 0 ) {
				$imgUrl = $this->saveImage($certificateImg);
			} else {
				$imgUrl = $certificateImg;
			}
		}
		$m = M("Dealer");
		if ( false !== $m->where("id=%d and cid=%d", $agentId, $this->aid)->save(array('certificateConfig'=>$config, 'certificateImg'=>$imgUrl)) ) {
			$this->ajaxSuccess("配置保存成功");
			$m = M("DistributionShopCertificate");
			$certificate = $m->where('cid=%d and type=%d', $this->aid, 2)->find();
			if ( $certificate == null ) {
				$certificate = array(
						'cid' => $this->aid,
						'img' => $img,
						'type' => 2,
						'config' => $config,
				);
				$id = $m->add($certificate);
			}
			$this->ajaxSuccess("配置保存成功");
		} else {
			$this->ajaxError("配置保存失败"); 
		}
	}
	
	/**
	 * 代理商证书设置
	 */
	public function agentIndexAction() {
		$type = 1;
		$agentId = I("id", 0, "intval");
		$agent = M("Agent")->where("id=%d and cid=%d", $agentId, $this->aid)->find();
		if ( $agent ) {
			/* 默认设置 */
			$m = M("DistributionShopCertificate");
			$distributionShopCertificate = $m->where('cid=%d and type=%d', $this->aid, $type)->find();
			$agent['certificate_img'] = $distributionShopCertificate['img'];
			/* 代理配置 */
			if ( empty($agent['certificateConfig']) ) {
				$agent['certificateConfig'] = unserialize($distributionShopCertificate['config']);
			} else {
				$agent['certificateConfig'] = unserialize($agent['certificateConfig']);
			}
			$agent['jsonConfig'] = json_encode($agent['certificateConfig']);
		} else {
			$this->error("未找到代理商,请先选择代理商再进入证书设置.");
		}
		$this->assign("agent", $agent);
		$this->display();
	}
	
	/**
	 * 代理商证书提交设置
	 */
	public function agentIndexPostAction() {
		$agentId = I("id", 0, "intval");
		$config = I("config", array());
		$config = serialize($config);
		$img = I("img", "");
		$certificateImg = I("certificateImg", "");
		if ($certificateImg) {
			if ( strpos($certificateImg, 'http') !== 0 ) {
				$imgUrl = $this->saveImage($certificateImg);
			} else {
				$imgUrl = $certificateImg;
			}
		}
		$m = M("Agent");
		if ( false !== $m->where("id=%d and cid=%d", $agentId, $this->aid)->save(array('certificateConfig'=>$config, 'certificateImg'=>$imgUrl)) ) {
			$this->ajaxSuccess("配置保存成功");
			$m = M("DistributionShopCertificate");
			$distributionShopCertificate = $m->where('cid=%d and type=%d', $this->aid, 1)->find();
			if ( $distributionShopCertificate == null ) {
				$distributionShopCertificate = array(
						'cid' => $this->aid,
						'img' => $img,
						'type' => 1,
						'config' => $config,
				);
				$id = $m->add($distributionShopCertificate);
			}
			$this->ajaxSuccess("配置保存成功");
		} else {
			$this->ajaxError("配置保存失败");
		}
	}
	
	/**
	 * HEX to RGB
	 * @param unknown $colour
	 * @return boolean|multitype:number
	 */
	private function hex2rgb( $colour ) {
		if ($colour [0] == '#') {
			$colour = substr ( $colour, 1 );
		}
		if (strlen ( $colour ) == 6) {
			list ( $r, $g, $b ) = array ($colour [0] . $colour [1], $colour [2] . $colour [3], $colour [4] . $colour [5] );
		} elseif (strlen ( $colour ) == 3) {
			list ( $r, $g, $b ) = array ($colour [0] . $colour [0], $colour [1] . $colour [1], $colour [2] . $colour [2] );
		} else {
			return false;
		}
		$r = hexdec ( $r );
		$g = hexdec ( $g );
		$b = hexdec ( $b );
		return array ('red' => $r, 'green' => $g, 'blue' => $b );
	}
	
	/**
	 * 预览
	 */
	public function previewCertificateAction() {
		$agentId = I("id", 0, "intval");
		$config = I("config", array());
		$imgUrl = I("img", "") or $this->ajaxError("请先上传证书图片");
		$imgUrl = preg_replace('/http:\/\/[^\/]+/', "saestor://wmei5", $imgUrl);
		$imgInfo = getimagesize($imgUrl);
		
		$fun = str_replace('/', 'createfrom', $imgInfo['mime']);
		$im = $fun($imgUrl);
		foreach( $config as $v ) {
			$color = ImageColorAllocate($im, 0, 0, 0);
			if ( !empty($v['color']) ) {
				$res = $this->hex2rgb($v['color']);
				$color = ImageColorAllocate($im, $res['red'], $res['green'], $res['blue']);
			}
			//$txt = iconv("gb2312","utf-8", $v['label']);
			imagettftext($im, 15, 0, $v['pos'][0], $v['pos'][1]+30, $color, SAE_Font_MicroHei, $v['value']);
		}
		
		ob_start();
		imagejpeg( $im );
		$imgstr = ob_get_contents();
		ob_end_clean();
		imagedestroy( $im );

		$ext = pathinfo($imgUrl, PATHINFO_EXTENSION);
		$base64 = "data:".$imgInfo['mime'].";base64,".base64_encode($imgstr);
		$this->ajaxSuccess("", array('img' => $base64));
	}
	
	private function createText($instring) {
		$outstring="";
		$max=strlen($instring);
		for( $i=0;$i<$max;$i++ ) {
			$h=ord($instring[$i]);
			if($h>=160 && $i<$max-1)
			{
				$outstring.="&#".base_convert(bin2hex(iconv("gb2312","ucs-2",substr($instring,$i,2))),16,10).";";
				$i++;
			} else {
				$outstring.=$instring[$i];
			}
		}
		return $outstring;
	}
	
	/**
	 * 存储图像
	 * @param unknown $base64
	 * @return unknown
	 */
	private function saveImage( $base64 ) {
		$base64_image_content = $base64;
		$domain = C('UPLOAD_DOMAIN');
		if( $base64_image_content and preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
			$type = $result[2];
			$filePath = date("Y-m-d")."/". date('YmdHis') . rand(1234, 9999) . rand(1234, 9999).".{$type}";
			$s = new \SaeStorage();
			$img = base64_decode(  str_replace($result[1], '', $base64_image_content) );
			$s->write($domain, $filePath, $img);
			$url = $s->getUrl($domain, $filePath);
		}
		return $url;
	}
	
}